package pdfmerge;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;

public class MergeFile {
	/**
	 * 合並pdf文件 
	 * 
	 * @param files 要合並文件數組(絕對路徑如{ "e:\\1.pdf", "e:\\2.pdf" ,"e:\\3.pdf"}) *
	 * 
	 * @param newfile 合並後新產生的文件絕對路徑如e:\\temp.pdf
	 * 
	 * @return boolean 產生成功返回true, 否則返回false
	 */
	public static void main(String[] args) {
		String[] files = { "C:/Users/xiongfei/Desktop/042001800311-16253272.pdf",
				"C:/Users/xiongfei/Desktop/031001800211-94184096.pdf"};
		String savepath = "C:\\Users\\xiongfei\\Desktop/发票.pdf";
		
		mergePdfFiles(files, savepath);
		
		// mergePdfFilesInDirs("C:\\Users\\xiongfei\\Desktop\\star", savepath);
		
		
	}

	/**
	 * 合并多个pdf文件
	 * @param files
	 * @param newfile
	 * @return
	 */
	public static boolean mergePdfFiles(String[] files, String newfile) {
		boolean retValue = false;
		Document document = null;
		try {
			document = new Document(new PdfReader(files[0]).getPageSize(1));
			PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
			document.open();
			for (int i = 0; i < files.length; i++) {
				PdfReader reader = new PdfReader(files[i]);
				int n = reader.getNumberOfPages();
				for (int j = 1; j <= n; j++) {
					// document.newPage();
					PdfImportedPage page = copy.getImportedPage(reader, j);
					copy.addPage(page);
				}
			}
			retValue = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			document.close();
		}
		return retValue;
	}
	
	/**
	 * 合并某个目录下的pdf文件
	 * 
	 * @param files
	 * @param newfile
	 * @return
	 */
	public static boolean mergePdfFilesInDirs(String dirs, String newfile) {
		boolean retValue = false;
		Document document = null;
		
		Collection<File> files = FileUtils.listFiles(new File(dirs), null, false);
		
		File file0 = (File) CollectionUtils.get(files, 0);
		try {
			document = new Document(new PdfReader(new FileInputStream(file0)).getPageSize(1));
			PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
			document.open();
			for (int i = 0; i < files.size(); i++) {
				PdfReader reader = new PdfReader(new FileInputStream((File) CollectionUtils.get(files, i)));
				int n = reader.getNumberOfPages();
				for (int j = 1; j <= n; j++) {
					// document.newPage();
					PdfImportedPage page = copy.getImportedPage(reader, j);
					copy.addPage(page);
				}
			}
			retValue = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			document.close();
		}
		return retValue;
	}
}
